#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <string>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char **argv)
{
    if (argc != 3)
    {
        std::cout << "Usage: ip port" << argv[0] << std::endl;
    }
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "socket create error:" << errno << std::endl;
        return 1;
    }
    //客户端不需要显示绑定ip和port，OS会给你绑定好

    //要发给谁的ip和port
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    addr.sin_port = htons(atoi(argv[2]));
    socklen_t addrlen = sizeof(addr);
    while (1)
    {
        //发送什么数据
        std::string str;
        std::cout << "发送：";
        std::cin >> str;
        //最后两个参数就是告知OS，要发给的是谁
        sendto(sock, str.c_str(), str.size(), 0, (struct sockaddr *)&addr, addrlen);
        //此处tmp就是一个”占位符“
        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        char buf[1024] = {0};
        ssize_t cnt = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr *)&addr, &addrlen);
        if (cnt > 0) //成功接收到对方发过来的数据
        {
            //如何处理数据呢？
            //这里我们默认把发过来的数据当成字符串处理所以给数据末尾加个\0
            buf[cnt] = '\0';
            std::cout << "server echo# " << buf << std::endl;
        }
        else
        {
            //
        }
    }
    return 0;
}
